var app = getApp(), fetchApi = require("../../../utils/httpPost.js"), common_Js = require("../../../component/common.js")
import Dialog from '../../../component/vant/dialog/dialog';
import Toast from '../../../component/vant/toast/toast';
var context = null;// 使用 wx.createContext 获取绘图上下文 context
var isButtonDown = false;//是否在绘制中
var arrx = [];//动作横坐标
var arry = [];//动作纵坐标
var arrz = [];//总做状态，标识按下到抬起的一个组合
var canvasw = 0;//画布宽度
var canvash = 0;//画布高度



Page({
  /**
   * 页面的初始数据
   */
  data: {
    recordList:[],
    hasData:false,
    loading: false,
    netWork: false,
    isLoading: true,
    fire_work_id:0,
    fireWork:{},
    analyses:[],
    measures:[],
    user_type:'',
    signImg:'',
    fileList1:[],
    user_id:0,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.id){
      this.data.fire_work_id = parseInt(options.id)
    }
    this.startCanvas();
    this.onHttpInit();
    this.data.user_id = app.getStorageSync("user_id");
  },
  onShow(){
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpInit: function () {
    var that = this
    fetchApi.httpPost('/fire/work/detail', {
      work_id:that.data.fire_work_id,
    }, function (res) {
      console.log("作业票详情返回数据", res)
      if (res.data.code == 0) {
          that.data.fireWork = res.data.data.fireWork;
          that.data.measures = res.data.data.fireWork.measures;
          that.data.user_type =  res.data.data.user_type;
          if(that.data.fireWork.recordType == 0){
            wx.setNavigationBarTitle({
              title: '动火安全措施排查',
            })
          } else if(that.data.fireWork.recordType == 1){
            wx.setNavigationBarTitle({
              title: '有限空间安全措施排查',
            })
          } else if(that.data.fireWork.recordType == 2){
            wx.setNavigationBarTitle({
              title: '高空安全措施排查',
            })
          }
        that.setData({
          hasData: true,
          fireWork: res.data.data.fireWork,
          measures:res.data.data.fireWork.measures,
        })
      }
      that.setData({
         isLoading: false, loading: true, netWork: true,
      })
    }, function (res) {
        that.setData({ hasData: false,  isLoading: false,  loading: true, netWork: true })
    })
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  goAddAnalysis(){
      wx.navigateTo({
        url: './add/index?workId=' + this.data.fireWork.id,
      })
  },
  onChangeMeasure(e){
    // console.log('measures ==== ',this.data.measures)
    // console.log('onChangeMeasure',e);
    var value = e.detail;
    var item = e.currentTarget.dataset.item;
    var index = e.currentTarget.dataset.index;
    this.data.measures[index].answer = value;
    this.setData({
        measures: this.data.measures,
    })
  },
  bindInput(e){
    // console.log('bindInput',e);    
    var value = e.detail;
    var item = e.currentTarget.dataset.item;
    var index = e.currentTarget.dataset.index;
    this.data.measures[index].answer = value;
  },
  
  submitOp(){
    var measures = this.data.measures; 
    var count = 0;
    for(var index in measures){
        var measure = measures[index];
        if(measure.answer == undefined){
            Toast('第' + (parseInt(index)  + 1) + '项未填入结果');
            count++;
            return;
        }
    }

    if(this.data.fileList1.length < 2){
      Toast("请上传不少于2张现场图片");
      return;
    }

    if(this.data.signImg == ''){
      Toast("请签名并确认签名");
      return;
    }
    
    if(count == 0){
        this.onHttpSubmit();
    }
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpSubmit: function (e) {
    var that = this;
    fetchApi.httpPost('/fire/work/check/measures', {
        measures:that.data.measures,
        work_id: that.data.fire_work_id,
        user_type: that.data.user_type,
        sign_img: that.data.signImg,
    }, function (res) {
      console.log("发起申请响应数据", res)
      if (res.data.code == 0) {
          Toast.success(res.data.msg);
          if (that.data.fileList1.length > 0) {
            var count = 0;
            for (var index in that.data.fileList1) {
              wx.uploadFile({
                url: fetchApi.getPlatformUrl() + '/fire/work/uploadImg',
                filePath: that.data.fileList1[index].url,
                name: 'file',
                formData: {
                  fire_work_id: that.data.fire_work_id,
                  img_type:0,
                },
                success: function (res) {
                  console.log('uploadFile success res', res)
                  var dataJson = JSON.parse(res.data);
                  if(dataJson.code == 0){
                      count++;
                  }
                  if(count == that.data.fileList1.length){
                      Toast.success("上传成功");
                      setTimeout(function(){
                        wx.navigateBack({
                            delta: -1
                        })
                      },500)
                  }
                },
                fail: function (res) {
                  console.log('uploadFile fail res', res)
                }
              })
            }
          }

          setTimeout(function(){
              wx.navigateBack({
                  delta: -1
              })
          },500)
      }else{
        Toast.fail(res.data.msg);
      }
      that.setData({
         isLoading: false, loading: true, netWork: true,
      })
    }, function (res) {
        that.setData({ hasData: false,  isLoading: false,  loading: true, netWork: true })
    })
  },


  deleteImg1: function (res) {
    console.log('删除图片', res)
    var index = res.currentTarget.dataset.index;
    this.data.fileList1 = [];
    this.setData({
      fileList1: this.data.fileList1
    });
  },
  afterRead(event) {
    console.log('afterRead', event)
    const {
      file,
      name
    } = event.detail;
    console.log('afterRead name', name)
    console.log('afterRead file', file)
    const fileList = this.data[`fileList${name}`];

    this.setData({
      [`fileList${name}`]: fileList.concat(file)
    });

    console.log('afterRead fileList', fileList)
    this.data.fileList1.concat(file)
    console.log('fileList', this.data.fileList1)
  },


  

  /**
  * 以下 - 手写签名 / 上传签名
  */
 startCanvas: function () {//画布初始化执行
  var that = this;
  //获取系统信息
  wx.getSystemInfo({
   success: function (res) {
    canvasw = res.windowWidth;
    canvash = res.windowHeight;
    that.setData({ canvasw: canvasw });
    that.setData({ canvash: canvash });
   }
  }); 
  this.initCanvas();
  this.cleardraw(); 
  },
  //初始化函数
  initCanvas: function () {
    context = wx.createCanvasContext('canvas');
    context.beginPath()
    context.fillStyle = 'rgba(255, 255, 255, 0)';
    context.setStrokeStyle('#000000');
    context.setLineWidth(4);
    context.setLineCap('round');
    context.setLineJoin('round');
  },
  canvasStart: function (event) {
    isButtonDown = true;
    arrz.push(0);
    arrx.push(event.changedTouches[0].x);
    arry.push(event.changedTouches[0].y);
  },
  canvasMove: function (event) {
    if (isButtonDown) {
      arrz.push(1);
      arrx.push(event.changedTouches[0].x);
      arry.push(event.changedTouches[0].y);
    }
    for (var i = 0; i < arrx.length; i++) {
      if (arrz[i] == 0) {
        context.moveTo(arrx[i], arry[i])
      } else {
        context.lineTo(arrx[i], arry[i])
      }
    }
    context.clearRect(0, 0, canvasw, canvash);
    context.setStrokeStyle('#000000');
    context.setLineWidth(4);
    context.setLineCap('round');
    context.setLineJoin('round');
    context.stroke();
    context.draw(false);
  },
  canvasEnd: function (event) {
    isButtonDown = false;
  },
  //清除画布
  cleardraw: function () {
    arrx = [];
    arry = [];
    arrz = [];
    context.clearRect(0, 0, canvasw, canvash);
    context.draw(true);
  },
  uploadSignImg(mer_id){
      var that = this
      //生成图片
      wx.canvasToTempFilePath({
        canvasId: 'canvas',
        //设置输出图片的宽高
        // destWidth:150, 
        // destHeight:150,
        // fileType:'jpg',
        quality:1.0,
        success: function (res) {
          console.log(res)
          // canvas图片地址 res.tempFilePath
          that.data.signImg = res.tempFilePath;
          wx.uploadFile({
            url: fetchApi.getPlatformUrl() + '/fire/work/uploadSign',
            filePath: res.tempFilePath,
            name: 'file',
            formData: {
              user_id: that.data.user_id,
            },
            success: function (res) {
              console.log('uploadFile success res', res);
              var dataJson = JSON.parse(res.data);
              if(dataJson.code == 0){
                that.data.signImg = dataJson.data.file_name;
                Toast("已上传成功，请处理下一步");
              }
              console.log('that.data.signImg',that.data.signImg)
            },
            fail: function (res) {
              console.log('uploadFile fail res', res)
            }
          })

        },
        fail: function () {
          wx.showModal({
            title: '提示',
            content: 'canvas生成图片失败。微信当前版本不支持，请更新到最新版本！',
            showCancel: false
          });
        },
        complete: function () {}
      })
  }

})